package sso.utill;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

public class JwtUtils {
    //密钥
     private static  String secret = "AABBCCDD";

    /*1.基于负载和算法创建token令牌*/
    public static String generatorToken(Map<String,Object> map){
        String token = Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis()+3600))
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
        return token;
    }

    /*2.解析token获取数据*/
    public static Claims getClaimsFromToken(String token){
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();

    }

    /*3.判定token是否过期 */
    public static boolean isTokenExpired(String token){
        Date expiration = getClaimsFromToken(token).getExpiration();
        return expiration.before(new Date());
    }

    /*4.为指定用户生成token令牌*/
    public static String generateToken(Map<String,Object> claims){
        Date createdTime = new Date();
        Date expirationTime = new Date(System.currentTimeMillis()+3600*1000);
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(createdTime)
                .setExpiration(expirationTime)
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }
}
